package com.googlecode.imule.apps.util;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

import org.xml.sax.SAXException;

import com.googlecode.imule.apps.X;
import com.googlecode.imule.data.Parse;
import com.googlecode.imule.data.UDPCommunicationX;
import com.googlecode.imule.discovery.DiscoveryServiceX;

/**
 * The ListenerThread monitors a the command line for input coming in.
 * 
 * TODO: Remove from code base. Purely here for test purposes
 * 
 * @author Graeme Stevenson
 * @author Graham Williamson
 * @author Neil Cowzer
 */
public class ListenerX extends Thread {
	/** Indicates if this thread should shut down */
	private boolean shutdown;
	
	// the owner of this thread
	private X owner;
	
	private DatagramSocket inSocket;
	
	private DatagramPacket packet;
	
	/**
	 * Creates a new listener thread to monitor a socket.
	 */
	public ListenerX(X owner, UDPCommunicationX communication) {
		this.shutdown = false;
		this.owner = owner;
		this.inSocket = communication.getInSocket();
		this.packet = communication.getInfoPacket();
		
		System.out.println("setup");
	}
	
	public String makeAction(String xml){
		String action = "";
		try {
			action =  Parse.action(xml).toString();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}
		return action;
	}
	
	/**
	 * The run method monitors the socket for incoming data, printing whatever
	 * it gets...
	 */
	public void run() {
		while (!shouldShutdown()) {
			try {
				inSocket.receive(packet);
				//System.out.println(packet.getAddress() +", "+ packet.getPort());
				// replace with owner.execute()
				owner.execute((new String(packet.getData(), 0, packet.getLength())));
			} catch (Exception e) {
				System.out.println("error");
				e.printStackTrace();
				break; // terminate thread
			}
		}
	}

	/**
	 * Check if we should shutdown the listener thread.
	 * @return true if we should shutdown; false otherwise.
	 */
	public synchronized boolean shouldShutdown() {
		return shutdown;
	}
	
	/**
	 * Notify this listener thread that it should shutdown.
	 */
	public synchronized void shutdown() {
		shutdown = true;
	}

}
